package com.cheil.publish.service.publish;

import com.cheil.publish.service.data.ChatsDto;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.ElementHandle;
import com.microsoft.playwright.Locator;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.options.AriaRole;
import com.microsoft.playwright.options.LoadState;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Log4j2
@Component
@AllArgsConstructor
public class AutoPublishService {

    private final BrowserContext browser;

    private static Map<String, Page> contextMap = new HashMap<>();

    public String login() throws InterruptedException {
        Page page = contextMap.get("login");
        if (browser.pages().isEmpty()) {
            page = browser.newPage();
            contextMap.put("login", page);
        } else {
            page = browser.pages().getFirst();
            contextMap.put("login", page);
        }

        page.navigate("https://creator.xiaohongshu.com/login?selfLogout=true");
        page.waitForLoadState(LoadState.DOMCONTENTLOADED);
        page.locator("img").click();
        TimeUnit.SECONDS.sleep(2);
        ElementHandle elementHandle = page.waitForSelector("img[class='css-1lhmg90']");
        String src = elementHandle.getAttribute("src");
        log.info("src:{}", src);
        return src;

//        return page.screenshot(new ScreenshotOptions().setType(ScreenshotType.PNG));
    }

    public void publish(ChatsDto chatsDto) {
        try {

            // 读取终端输入的信息
//            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
//            System.out.println("请扫描二维码:");
//            try {
//                String input = reader.readLine();
//                System.out.println("您输入的内容是: " + input);
//            } catch (IOException e) {
//                System.err.println("读取输入时出错: " + e.getMessage());
//            }
            // 下载网络图片到本地临时文件
            Page page = contextMap.get("publish");
            if (browser.pages().isEmpty()) {
                page = browser.newPage();
                contextMap.put("publish", page);
            } else {
                page = browser.pages().getFirst();
                contextMap.put("publish", page);
            }
            Path tempImageFile = downloadImage(chatsDto.imageUrl());
            log.info("图片下载完成: {}", tempImageFile);
            page.navigate("https://creator.xiaohongshu.com/new/home");
            page.waitForLoadState(LoadState.NETWORKIDLE);
            page.getByText("发布笔记").click();
            page.waitForLoadState(LoadState.NETWORKIDLE);

            page.locator("div").filter(new Locator.FilterOptions().setHasText(Pattern.compile("^上传图文$"))).nth(1).click();
            page.waitForLoadState(LoadState.NETWORKIDLE);
            page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Choose File"))
                    .setInputFiles(new Path[]{tempImageFile});
            log.info("上传图片完成");
            page.waitForLoadState(LoadState.NETWORKIDLE);

            page.getByPlaceholder("填写标题会有更多赞哦～").click();
            page.getByPlaceholder("填写标题会有更多赞哦～").fill(chatsDto.title());
            log.info("填写标题完成");
            page.waitForLoadState(LoadState.NETWORKIDLE);
            page.getByRole(AriaRole.TEXTBOX).nth(1).click();
            page.waitForLoadState(LoadState.NETWORKIDLE);
            page.getByRole(AriaRole.TEXTBOX).nth(1).fill(chatsDto.content());
            log.info("填写内容完成");
//            page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("发布")).click();
//            page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("发布")).click();
//            page.locator("div").filter(new Locator.FilterOptions().setHasText(Pattern.compile("^发布$"))).nth(6).click();
//            page.locator(".submit").first().click();
//            page.locator("label").filter(new Locator.FilterOptions().setHasText("定时发布")).locator("span").nth(1).click();
//            page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("定时发布")).click();
            TimeUnit.SECONDS.sleep(10);
            page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("发布")).click();

            TimeUnit.SECONDS.sleep(2);

            log.info("发布成功");


        } catch (IOException | InterruptedException e) {
            log.error("发布失败", e);
            throw new RuntimeException(e);
        }
    }


    public void publish(ChatsDto chatsDto, List<MultipartFile> images) {
        try {

            // 读取终端输入的信息
//            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
//            System.out.println("请扫描二维码:");
//            try {
//                String input = reader.readLine();
//                System.out.println("您输入的内容是: " + input);
//            } catch (IOException e) {
//                System.err.println("读取输入时出错: " + e.getMessage());
//            }
            List<Path> tempImageFiles = new ArrayList<>();
            // 下载网络图片到本地临时文件
            for (MultipartFile image : images) {
                try {
                    // 1. create temp file with correct extension
                    String ext = image.getOriginalFilename()
                            .substring(image.getOriginalFilename().lastIndexOf('.'));
                    Path temp = Files.createTempFile("xhs_", ext);
                    // 2. copy bytes from MultipartFile to temp file
                    image.transferTo(temp.toFile());
                    tempImageFiles.add(temp);
                } catch (Exception e) {
                    log.error("图片下载失败", e);
                }
            }
            Page page = browser.newPage();
            log.info("图片下载完成: {}", images);
            page.navigate("https://creator.xiaohongshu.com/new/home");
            page.waitForLoadState(LoadState.DOMCONTENTLOADED);
            page.getByText("发布笔记").click();
            page.waitForLoadState(LoadState.DOMCONTENTLOADED);

            page.locator("div").filter(new Locator.FilterOptions().setHasText(Pattern.compile("^上传图文$"))).nth(1).click();
            page.waitForLoadState(LoadState.DOMCONTENTLOADED);
            page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Choose File"))
                    .setInputFiles(tempImageFiles.toArray(new Path[0]));
            log.info("上传图片完成");
            page.waitForLoadState(LoadState.DOMCONTENTLOADED);

            page.getByPlaceholder("填写标题会有更多赞哦～").click();
            page.getByPlaceholder("填写标题会有更多赞哦～").fill(chatsDto.title());
            log.info("填写标题完成");
            page.waitForLoadState(LoadState.DOMCONTENTLOADED);
            page.getByRole(AriaRole.TEXTBOX).nth(1).click();
            page.waitForLoadState(LoadState.DOMCONTENTLOADED);
            page.getByRole(AriaRole.TEXTBOX).nth(1).fill(chatsDto.content());
            log.info("填写内容完成");
//            page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("发布")).click();
//            page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("发布")).click();
//            page.locator("div").filter(new Locator.FilterOptions().setHasText(Pattern.compile("^发布$"))).nth(6).click();
//            page.locator(".submit").first().click();
//            page.locator("label").filter(new Locator.FilterOptions().setHasText("定时发布")).locator("span").nth(1).click();
//            page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("定时发布")).click();
            TimeUnit.SECONDS.sleep(10);
            page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("发布")).click();

            TimeUnit.SECONDS.sleep(2);

            log.info("发布成功");


        } catch (InterruptedException e) {
            log.error("发布失败", e);
            throw new RuntimeException(e);
        }
    }


    private Path downloadImage(String imageUrl) throws IOException {
        URL url = new URL(imageUrl);
        URLConnection connection = url.openConnection();
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");

        try (InputStream in = connection.getInputStream()) {
            // 创建临时文件
            Path tempFile = Files.createTempFile("xhs_image_", ".png");
            // 将网络图片内容复制到临时文件
            Files.copy(in, tempFile, StandardCopyOption.REPLACE_EXISTING);
            return tempFile;
        }
    }

    public static void main(String[] args) throws URISyntaxException {
        Path path = Paths.get(
                new URI("https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/7d/1c/20250909/a25719eb/f6f905f4-6fc6-4790-8eb5-7f7ca6931895-1.png?Expires=1757985250&OSSAccessKeyId=LTAI5tDUB1cEqFCYhEwWry26&Signature=eNBJAHAFPnzvmsMHmgrPDbk7y%2Bs%3D"));
        log.info("{}", path);
    }

//
//    public static void main(String[] args) {
//
//        try (Playwright playwright = Playwright.create()) {
//            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions()
//                    .setHeadless(false));
//            BrowserContext context = browser.newContext();
//            Page page = context.newPage();
//            page.navigate("https://creator.xiaohongshu.com/login?selfLogout=true");
//
//            TimeUnit.SECONDS.sleep(2);
//            page.locator("img").click();
//            TimeUnit.SECONDS.sleep(2);
//            page.screenshot(new ScreenshotOptions().setPath(Paths.get("screenshot-webkit.png")));
//
//            // 读取终端输入的信息
//            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
//            System.out.println("请扫描二维码:");
//            try {
//                String input = reader.readLine();
//                System.out.println("您输入的内容是: " + input);
//            } catch (IOException e) {
//                System.err.println("读取输入时出错: " + e.getMessage());
//            }
//
//            page.navigate("https://creator.xiaohongshu.com/new/home");
//            page.getByText("发布笔记").click();
//            page.locator("div").filter(new Locator.FilterOptions().setHasText(Pattern.compile("^上传图文$"))).nth(1).click();
//
//            page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Choose File"))
//                    .setInputFiles(new Path[]{Paths.get("screenshot-webkit.png")});
//            log.info("上传图片完成");
//            TimeUnit.SECONDS.sleep(2);
//
//            page.getByPlaceholder("填写标题会有更多赞哦～").click();
//            page.getByPlaceholder("填写标题会有更多赞哦～").fill("111");
//            log.info("填写标题完成");
//            TimeUnit.SECONDS.sleep(2);
//            page.getByRole(AriaRole.TEXTBOX).nth(1).click();
//            TimeUnit.SECONDS.sleep(2);
//            page.getByRole(AriaRole.TEXTBOX).nth(1).fill("2222");
//            log.info("填写内容完成");
//            page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("发布")).click();
//            TimeUnit.SECONDS.sleep(2);
//            log.info("发布成功");
//
//        } catch (InterruptedException e) {
//            log.error("发布失败", e);
//            throw new RuntimeException(e);
//        }
//
//    }


}